import { useSelector } from 'react-redux'
import { useLocation, Navigate } from 'react-router-dom'
import { rootRouter } from "@/router";
import { searchRoute } from "@/utils";
import { HOME_URL } from "@/config/config";

const AuthRouter = (props) => {
  const { token } = useSelector((state) => state.global)
  const { authRouter } = useSelector((state) => state.auth)
  const { pathname } = useLocation()
  const route = searchRoute(pathname, rootRouter)
  //  判断当前路由是否需要访问权限(不需要权限直接放行)
  if (!route.meta) return props.children
  if (!route.meta.requiresAuth) return props.children
  //  判断是否登录(未登录跳转到登录页)
  if (!token) return <Navigate to="/login" replace />
  const staticRouter = [HOME_URL, '/403']
  const routerList = authRouter.concat(staticRouter)
  if (routerList.indexOf(pathname) == -1) return <Navigate to="/403" />

  // * 当前账号有权限返回 Router，正常访问页面
  return props.children
}

export default AuthRouter
